import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import org.nanohttpd.util.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

public class HttpServer extends NanoHTTPD {

    public static final String TAG = "HttpServerImpl";
    private static final String REQUEST_ROOT = "/";
    private static final String REQUEST_TEST = "/test";
    private static final String REQUEST_ACTION_GET_FILE = "/getFile";
    private static final String REQUEST_ACTION_GET_FILE_LIST = "/getFileList";

    public HttpServer(String ip,int port){
        super(ip,port);
    }

    @Override
    protected Response serve(IHTTPSession session) {
        String strUri = session.getUri();
        String method = session.getMethod().name();
        System.out.println("Response serve uri = " + strUri + ", method = " + method);

        if(REQUEST_ROOT.equals(strUri)) {// 根目录
            return responseRootPage(session);
        }else if(REQUEST_TEST.equals(strUri)){// 返回给调用端json串
            return responseJson();
        }else if(REQUEST_ACTION_GET_FILE_LIST.equals(strUri)){// 获取文件列表
            @SuppressWarnings("deprecation")
            Map<String,String> params = session.getParms();

            String dirPath = params.get("dirPath");
            if(dirPath != null&&dirPath.length() > 0){
                return responseFileList(session,dirPath);
            }
        }else if(REQUEST_ACTION_GET_FILE.equals(strUri)){ // 下载文件
            @SuppressWarnings("deprecation")
            Map<String,String> params = session.getParms();
            // 下载的文件名称
            String fileName = params.get("fileName");
            File file = new File(fileName);

            if(file.exists()){
                if(file.isDirectory()){
                    return responseFileList(session,fileName);
                }else{
                    return responseFileStream(session,fileName);
                }
            }else{
                System.out.println("try to download file but not found :" + fileName);
            }
        }
        return response404(session);
    }


    private Response responseRootPage(IHTTPSession session) {

        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("test! \n");
        builder.append("</body></html>\n");
        return Response.newFixedLengthResponse(builder.toString());
    }

    /**
     * 提供给终端进行文件下载
     * @param session
     * @param filePath
     * @return
     */
    private Response responseFileStream(IHTTPSession session,String filePath) {
        System.out.println("responseFileStream() ,fileName = " + filePath);
        try {
            FileInputStream fis = new FileInputStream(filePath);
            return Response.newChunkedResponse(Status.OK, "application/octet-stream", fis);
        }
        catch (FileNotFoundException e) {
            System.out.println("responseFileStream FileNotFoundException :"+e.getMessage());
            return response404(session);
        }
    }

    /**
     *
     * @param session http请求
     * @param dirPath 文件夹路径名称
     * @return
     */
    private Response responseFileList(IHTTPSession session,String dirPath) {
        System.out.println("responseFileList() , dirPath = " + dirPath);
        List<String> fileList = FileUtils.getFilePaths(dirPath, false);

        if (fileList == null) {
            return response404(session);
        }else {
            StringBuilder sb = new StringBuilder();
            for(String filePath : fileList){
                sb.append("<a href=" + REQUEST_ACTION_GET_FILE + "?fileName=" + filePath + ">" + filePath + "</a>" + "<br>");
            }
            return Response.newFixedLengthResponse(sb.toString());
        }
    }

    /**
     * 调用的路径出错
     * @param session
     * @return
     */
    private Response response404(IHTTPSession session) {
        String url = session.getUri();
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("Sorry, Can't Found "+url + " !");
        builder.append("</body></html>\n");
        System.out.println("response404 builder.toString()= " + builder.toString());
        return Response.newFixedLengthResponse(builder.toString());
    }

    /**
     * 返回给调用端json字符串
     * @return
     */
    private Response responseJson(){
        return Response.newFixedLengthResponse("调用成功");
    }
}
